package org.example.order.controller;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.example.order.VO.LoginVO;
import org.example.order.VO.RegisterVO;
import org.example.order.VO.AdminVO;
import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.example.order.entity.Ad;
import org.example.order.entity.Admin;
import org.example.order.permission.Access;
import org.example.order.permission.AccessLevel;
import org.example.order.service.impl.AdminServiceImpl;
import org.example.order.util.IpUtil;
import org.example.order.util.JWTUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private AdminServiceImpl AdminService;
    @Access(level = AccessLevel.ADMIN)
    @GetMapping("/selectAll")
    public APIResponse<List<Admin>> getAll(){
        List<Admin>list= AdminService.selectAll();
        return new APIResponse<>(ResponseCode.SUCCESS, "查询成功", list);
    }
    @Access(level = AccessLevel.ADMIN)
    @GetMapping("/selectById/{id}")
    public APIResponse<Admin> getAdminById(@PathVariable Integer id){
        Admin admin=AdminService.selectById(id);
        if(admin==null){
            return new APIResponse<>(ResponseCode.FAIL,"用户不存在");
        }
        return new APIResponse<Admin>(ResponseCode.SUCCESS, "查询成功", admin);
    }
    @Access(level = AccessLevel.LOGIN)
    @GetMapping("/selectPage")
    public APIResponse<PageInfo<Admin>> getAdminPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                                     @RequestParam(required = false) String keyword) {
        // 使用 PageHelper 设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 调用修改后的 service 方法获取数据列表
        List<Admin> adminList = AdminService.getAdminList(keyword);

        // 将结果封装到 PageInfo 对象
        PageInfo<Admin> pageInfo = new PageInfo<>(adminList);

        return new APIResponse<>(ResponseCode.SUCCESS, "查询成功", pageInfo);
    }
    @Access(level = AccessLevel.ADMIN)
    @PostMapping("/add")
    public APIResponse<Admin> register(@RequestBody @Valid RegisterVO registerVO){

        Admin Admin=AdminService.register(registerVO);
        return new APIResponse<Admin>(ResponseCode.SUCCESS,"注册成功",Admin);
    }

    @PostMapping("/login")
    public APIResponse<Map<String, Object>> login(@RequestBody @Valid LoginVO loginVO, HttpServletRequest request){
        String ip= IpUtil.getIpAddr(request);
        AdminVO AdminVO =AdminService.login(loginVO,ip);
        Map<String, Object> map=new HashMap<>();
        map.put("token",AdminVO.getToken());
        map.put("AdminInfo",AdminVO);
        return new APIResponse<>(ResponseCode.SUCCESS,"登录成功",map);
    }
    @Access(level = AccessLevel.ADMIN)
    @GetMapping("info")
    public APIResponse<Admin> getinfo(HttpServletRequest request){
        String token=request.getHeader("Authorization");
        System.out.println(token);
        System.out.println(request.getHeader("Authorization"));
        log.info("当前token为：[{}]",token);
        try {
            // 验证令牌
            DecodedJWT verify = JWTUtils.verify(token);
            Map<String, String> map=JWTUtils.getTokenData(token);
            log.info(map.get("id"));
            Admin admin=AdminService.getById(map.get("id"));
            return new APIResponse<>(ResponseCode.SUCCESS,"请求成功",admin);
        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"无效签名");
        }catch (TokenExpiredException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token过期");
        }catch (AlgorithmMismatchException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"算法不一致");

        }catch (Exception e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token无效！");
        }
    }
    @Access(level = AccessLevel.ADMIN)
    @PutMapping("/update")
    public APIResponse<String> updateAdminInfo(@RequestBody @Valid AdminVO Admin){
        String res=AdminService.updateAdminInfo(Admin);
        if (res.equals("修改成功"))
            return new APIResponse<>(ResponseCode.SUCCESS,"成功修改",res);
        else return new APIResponse<>(ResponseCode.FAIL,"修改失败",res);
    }
    @Access(level = AccessLevel.ADMIN)
    @PutMapping("/changePassword")
    public APIResponse<Boolean> updatePassword(@RequestParam Long AdminId,@RequestParam String oldPassword,@RequestParam String newPassword){
        boolean res=AdminService.updatePassword(AdminId,oldPassword,newPassword);
        return new APIResponse(ResponseCode.SUCCESS,"修改成功",res);
    }
    @Access(level = AccessLevel.ADMIN)
    @DeleteMapping("delete/{id}")
    public APIResponse<Boolean> removeAdmin(@PathVariable Long id) {
        boolean result = AdminService.removeAdmin(id);
        return new APIResponse(ResponseCode.SUCCESS,"修改成功",result);
    }

    /**
     * 批量删除用户（逻辑删除）
     */
    @Access(level = AccessLevel.ADMIN)
    @DeleteMapping("/delete/batch")
    public APIResponse<Boolean> removeAdminBatch(@RequestBody List<Long> ids) {
        boolean result =  AdminService.removeAdminBatch(ids);
        return new APIResponse(ResponseCode.SUCCESS,"修改成功",result);
    }

    /**
     * 恢复用户
     */
    @Access(level = AccessLevel.ADMIN)
    @PutMapping("/restore/{id}")
    public APIResponse<Boolean> restoreAdmin(@PathVariable Long id) {
        boolean result = AdminService.restoreAdmin(id);
        return new APIResponse(ResponseCode.SUCCESS,"修改成功",result);
    }

    /**
     * 批量恢复用户
     */
    @Access(level = AccessLevel.ADMIN)
    @PutMapping("/restore/batch")
    public APIResponse<Boolean> restoreAdminBatch(@RequestBody List<Long> ids) {
        boolean result = AdminService.restoreAdminBatch(ids);
        return new APIResponse(ResponseCode.SUCCESS,"修改成功",result);
    }
    @PostMapping("/test")
    public APIResponse test(String token){
        log.info("当前token为：[{}]",token);
        try {
            // 验证令牌
            DecodedJWT verify = JWTUtils.verify(token);
            Map<String, String> map=JWTUtils.getTokenData(token);
            return new APIResponse<>(ResponseCode.SUCCESS,"请求成功",map.get("id"));
        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"无效签名",false);
        }catch (TokenExpiredException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token过期",false);
        }catch (AlgorithmMismatchException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"算法不一致",false);

        }catch (Exception e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token无效！",false);
        }
    }
}
